

/**
 * Builds the form for this level
 * @param {Object} i_level
 * @param {Array} of games {match_id:<value> , home:<bool> , away:<bool>}
 */
function buildKnockoutBetForm(i_level, gamesArr) {
    var levelList = ["Group Stage" , "Final" , "Semi Final", "Quarter Final" , "1/8"];
     var gamesList = "";
     var allGamesArray = "";
     
    for (var i = 0; i < gamesArr.length; i++) {
        var homeStatus = true;
        var awayStatus = true;
        var openGameButton = false;
         //Return his old scores
          var oldScoresHome = 0;
          var oldWinner = "";
          var oldScoresAway = 0;
          
           if(gamesArr[i].score != null){
           //Maybe he doesn't have old scores??
           oldScoresHome = gamesArr[i].score[0];
           oldScoresAway = gamesArr[i].score[1];
         }
         
         if(i_level != 0){
             //This finds out which games should be disabled
           homeStatus = gamesArr[i].home;
           awayStatus = gamesArr[i].away;
           var isDisabledHome = "";
           var isDisabledAway = "";
           var isDisabledWinner = "";
           oldWinner = gamesArr[i].winner;
       
           //Disable home game
           if(!homeStatus){
               isDisabledHome = "disabled='true'";
               isDisabledWinner = "disabled='true'";
               oldScoresHome = 0;
               
               //Flips the openGame button to true
               openGameButton = !openGameButton;
               
           }
           //Disable away game
           if(!awayStatus){
               isDisabledAway = "disabled='true'";
               isDisabledWinner = "disabled='true'";
               oldScoresAway = 0;
               
               //Flips the openGame button to false if was true, and to true if was false
               openGameButton = !openGameButton;
           }
           
         }
          
          
        
        //Check if home or away are false, if so, disable something TODO, check this only if level not 0
        
        //First TD (teamA)
        gamesList += "<tr><td> " + map(i_level,gamesArr[i].match_id).home + "</td>";
       
       //Second TD (input)
        gamesList += "<td><input "+isDisabledHome+" type='number' min='0' class='form-control' style='width:45%; height:100%; padding:2px 2px 2px 2px' value='"+oldScoresHome+"' id='"+gamesArr[i].match_id+'_home'+"'>";
       
       //Third TD (input)
        gamesList += "</td><td><input "+isDisabledAway+" type='number' min='0' class='form-control' style='width:45%;height:100%; padding:2px 2px 2px 2px'' value='"+oldScoresAway+"' id='"+gamesArr[i].match_id+'_away'+"'></td>";
         
       //Fourth TD (teamB)
       gamesList += "<td>" + map(i_level,gamesArr[i].match_id).away + "</td>";
       
      
       
       //Fifth TD (in case you need to choose a winner)
       if(i_level != 0){
              gamesList += "<td><select  class='form-control' "+isDisabledWinner+" id='"+gamesArr[i].match_id+'_winner'+"'><option>Winner</option><option>"+map(i_level,gamesArr[i].match_id).home+"</option>";
        gamesList += "<option>"+map(i_level,gamesArr[i].match_id).away+"</option></select></td>";
        
            //Sixth TD (Open game button)
           //If ONE of the games is false - open this button
           if(openGameButton){
               gamesList += "<td><a href='#' class='btn btn-lg btn-info' onClick='openMatch("+ i_level +"," +JSON.stringify(gamesArr[i].match_id)+")'>Open?</a></td>";;
           }  
       }
        //Append end of row anyway
               gamesList += "</tr>";
        
       
        //Pushes this game to the array and sends it to submit function
        allGamesArray += gamesArr[i].match_id+"_";
    }
    
   //Setup popup text
  // $('#popupText').html("ההימור התקבל");
    
    var html = "<div><table class='table table-hover table-striped'>"+gamesList+"</table>\
     <a id='modal-129014' href='#modal-container-129014' role='button' class='btn' data-toggle='modal'> <button type='submit' class='btn btn-lg btn-info' onclick='submitKnockoutAndGroupBet("+i_level+", "+JSON.stringify(allGamesArray)+")'>\
                          Done!</button></a>\
               </div>";
   var rulesTable = ruleBuilder(i_level);
    document.getElementById('GroupAndKnockoutTableDiv').innerHTML = html;
    $('#rulesDiv').html(rulesTable);
    
    return html;
}

/**
 * Sets up the tournament betting page and puts it in the @GroupAndKnockoutTableDiv
 * @param All the tournament bets for this user
 */
function buildTournBetForm(betsObj){
    var oldKingOfAssists = "";
    var oldKingOfGoals = "";
    var oldChamp = "";
    if(betsObj.kingOfGoals != null || betsObj.champion != null){
        //Has old bets - put them up
        oldKingOfAssists = betsObj.kingOfAssists;
        oldKingOfGoals = betsObj.kingOfGoals;
        oldChamp = betsObj.champion;
    }
    var tourBets = "";
    var listOfTeams = "";
    var groups = ["World Cup, Group A", "World Cup, Group B", "World Cup, Group C", "World Cup, Group D", "World Cup, Group E", "World Cup, Group F", "World Cup, Group G", "World Cup, Group H"];
      
        //Creates a list of ALL teams for the champion select
       for (var i=0; i < groups.length; i++) {
         listOfTeams += mapChampions(groups[i],oldChamp);
        
       };
       //Last Other 
         listOfTeams += "<option> Other </option>";
       
       
       /*CHAMPION BET*/
        tourBets += " <div><table class='table table-hover table-striped'>";
          //Append Group Name
        tourBets += "<tr><td> Champions: </td><td><select  class='form-control' id='championSelect'>" + listOfTeams + "</select></td></tr>";
        
          //Append MVP Name
        tourBets += "<tr><td> Most Assists: </td><td><select class='form-control' id='inputMvp' required='required'>"+mapKingOfAssists(oldKingOfAssists)+"</select></td></tr>";
          //Append King of Goals Name
        tourBets += "<tr><td> Golden Boot: </td><td><select class='form-control' id='inputKingOfGoals' required='required'>"+mapKingOfGoals(oldKingOfGoals)+"</select></td></tr>";
        //Append another select of qualifiers
        tourBets += "</table></div>";
   
      //  $('#popupText').html("ההימור התקבל");

   var html = tourBets+ "<a id='modal-129014' href='#modal-container-129014' role='button' class='btn' data-toggle='modal'><button class='btn btn-lg btn-info' onclick='submitTournBet()'>\
                                    Go!\
                        </button></a>\
               </div>";
               
               $('#GroupAndKnockoutTableDiv').html(html);
               $('#rulesDiv').html(ruleBuilder(5));
}


/**
 * The betting form for the group stage - all groups in one form!
 * Needs to have the score, and the qualifiers for the level
 */
function buildQualifiersBetForm(){
    //window.location.href = "#modal-container-764081";
   var groups = ["World Cup, Group A", "World Cup, Group B", "World Cup, Group C", "World Cup, Group D", "World Cup, Group E", "World Cup, Group F", "World Cup, Group G", "World Cup, Group H"];
   var numOfQualifiers = 8;
   var qualifiersList = "";
   var oldRankedFirst = null;
   var oldRankedSecond = null;
   for(var i = 0 ; i < numOfQualifiers ; i++){
       var trimmed = groups[i].split(' ')[3];
       
       var oldQualifiers = localStorage.getItem('qualifier'+trimmed);
       if(oldQualifiers != null){
           //User has old qualifiers
            oldRankedFirst = oldQualifiers.split(',')[0].trim();
            oldRankedSecond = oldQualifiers.split(',')[1].trim();
       }
       
       
         //Append Group name
           qualifiersList += "<tr><td> " + groups[i].substring(groups[i].indexOf(',')+2,groups[i].length) + "</td>";
     
        //Append First list
        qualifiersList += "<td><select  class='form-control' id='"+trimmed+"_rankedFirst"+"'>" + mapQualifiers(groups[i],oldRankedFirst) + "</select>";
       
          
       
        //Append another select of qualifiers
        qualifiersList += "<td><select class='form-control' id='"+trimmed+"_rankedSecond"+"'>" + mapQualifiers(groups[i],oldRankedSecond) + "</select></td></tr>";
   }
   //  $('#popupText').html("ההימור התקבל");
   var html = "<div style='text-align:center'>\
                <table  class='table table-hover table-striped'><thead><tr><td>Group</td><td>First Place</td><td>Second Place</td></tr></thead>"+qualifiersList+"\
               </table><a id='modal-129014' href='#modal-container-129014' role='button' class='btn' data-toggle='modal'><button class='btn btn-lg btn-info' onclick='submitQualifiersBet()'>\
                                   Done!\
                        </button></a>\</div>";
               
               $('#GroupAndKnockoutTableDiv').html(html);
               $('#rulesDiv').html(ruleBuilder(-1));
    
}



/**
 * Maps between the group and the 4 teams, and appends it as HTML select options
 */
function mapQualifiers(groupName,selectedTeam){
    var teams = localStorage.getItem(groupName).split(',');
    var html = "";
    var makeDefault = "";
    for( var i = 0 ; i < teams.length ; i++){
           if(selectedTeam == teams[i]){
               makeDefault = "selected='selected'";
           }
        html += "<option "+makeDefault+">"+teams[i] +" </option>";
        var makeDefault = "";
    }
    return html;
    
}

/**
 * Maps between the group and the 4 teams, and appends it as HTML select options
 */
function mapChampions(groupName,selectedTeam){
    var teams = localStorage.getItem(groupName).split(',');
    var html = "";
    var makeDefault = "";
    for( var i = 0 ; i < teams.length ; i++){
           if(selectedTeam == teams[i]){
               makeDefault = "selected='selected'";
           }
           //Go over all ranked champions - if its NOT one of them - write other
           for(var j = 0 ; j< rankedChampions.length ; j++){
               var splitChamps = rankedChampions[j].split(",");
             if(splitChamps.indexOf(teams[i]) > -1){
                html += "<option "+makeDefault+">"+teams[i] +" </option>";
              }  
           }
           
       
        var makeDefault = "";
        
    }
    
    return html;
    
}
/**
 * Maps the top assister
 */
function mapKingOfAssists(oldChoice){
    var topAssists=["Angel Di Maria","Lionel Messi","Mesut Ozil","Neymar","Eden Hazard",
                    "Oscar","David Silva","Cesc Fabregas","Hulk","Thomas Muller","Arjen Robben",
                    "Cristiano Ronaldo","Diego Costa","Mario Gotze","Pedro","James Rodriguez","Wayne Rooney",
                    "Luis Suarez","Willian","Weslery Sneijder","Ivan Rakitic","Koke","Xavi Hernandez",
                    "Steven Gerrard","Andrea Pirlo","Bastian Schweinsteiger","Toni Kroos","André Schürrle",
                    "Joao Moutinho","Nani","Mathieu Valbuena","Sergio Aguero","Other"];
  //var teams = localStorage.getItem(groupName).split(',');
    var html = "";
    var makeDefault = "";
    for( var i = 0 ; i < topAssists.length ; i++){
           if(oldChoice == topAssists[i]){
              makeDefault = "selected='selected'";
           }
           html += "<option "+makeDefault+">"+topAssists[i] +" </option>";      
        var makeDefault = "";
        
    }
    
    return html; 
}


function mapKingOfGoals(oldChoice){
  var topScorers=["Lionel Messi","Neymar","Sergio Aguero","Cristiano Ronaldo","Gonzalo Higuain",
                  "Fred","Luis Suarez","Diego Costa","Romelu Lukaku","Karim Benzema","Thomas Muller",
                  "Robin van Persie","Mario Balotelli","Miroslav Klose","Hulk","Wayne Rooney","Edinson Cavani",
                  "Daniel Sturridge","Fernando Torres","Olivier Giroud","Arjen Robben","Eden Hazard",
                  "Lukas Podolski","David Villa","Mario Mandzukic","Pedro","Danny Welbeck","Antonio Cassano",
                  "Diego Forlan","Mario Götze","Weslery Sneijder","Andres Iniesta","Other"];
  //var teams = localStorage.getItem(groupName).split(',');
    var html = "";
    var makeDefault = "";
    for( var i = 0 ; i < topScorers.length ; i++){
           if(oldChoice == topScorers[i]){
               makeDefault = "selected='selected'";
           }
           html += "<option "+makeDefault+">"+topScorers[i] +" </option>";      
        var makeDefault = "";
        
    }
    
    return html;     
}



/**
 * Set of points rules
 */
var rules = [{
    level : 'Group',
    bullseye : 1,
    qualifier : 4,
    qualifierBullseye : 1,
    costToOpen : 0
}, {
    level : 'F',
    pointsToGive : 13,
    bullseye : 5,
    costToOpen : 13
}, {
    level : 'SF',
    pointsToGive : 11,
    bullseye : 4,
    costToOpen : 11
}, {
    level : 'QF',
    pointsToGive : 9,
    bullseye : 3,
    costToOpen : 9
}, {
    level : '1/8',
    pointsToGive : 7,
    bullseye : 2,
    costToOpen : 7
}, {
    level : 'Tournament Bets',
    kingOfAssists : 5,
    kingOfGoals : 5,
    champions : [4, 8, 12, 16]
}];


var rankedChampions = ["Brazil,Spain,Germany","Argentina,Italy,France","England,Uruguay,Netherlands","Other"];
/**
 * builds the rule div and puts it in the #rulesDiv
 * @param level 0-4, 0 is group, 1 is final, 2 is SF, 3 is QF, 4 is 1/8
 */
function ruleBuilder(level){
     var html="<table class='table table-hover table-striped' id='rulesTable'>";
    html += "<thead><th style='vertical-align: middle;'>Rules</th><th style='vertical-align: middle;'>pts</th></thead>";   
    
    
    if(level == 5){
         html+= "<tr><td>Top Assister</td><td>"+rules[level].kingOfAssists+" </td></tr>";
         html+= "<tr><td>Golden Boot</td><td>"+rules[level].kingOfGoals+"</td></tr>";
         
         
         //Append Ranked Champs
         for (var i=0; i < rankedChampions.length; i++) {
           html+= "<tr><td>"+ rankedChampions[i]+"</td><td>"+rules[level].champions[i]+"</td></tr>";
         };
         

         
    }
    
 
    
    
    if(level == -1){
        //Append Points for qualifiers
    html+= "<tr><td>Qualifiers</td><td>"+rules[0].qualifier+" </td></tr>";
    html+= "<tr><td>Exact Qualifiers</td><td>"+rules[0].qualifierBullseye+"</td></tr>";
    }
    else{
        
        if(level != 0 && level != 5){
             //Append points for winner
        html += "<tr><td>Correct Winner</td><td>"+rules[level].pointsToGive+" </td></tr>";
        }
       
         //Append Bullseye
         if(level != 5){
              html+= "<tr><td>Exact Score</td><td>"+rules[level].bullseye+" </td></tr>";
             html += "<tr><td>Cost to Open</td><td>"+rules[level].costToOpen+"  </td></tr>";
         }
       
    }
   
   
    html += "</table></div>";
     
    
    
    return html; 
}






// /**
 // * After bet has been made this is the alert
 // */
// function buildBetAlert(){
// var alertHTML ="<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>\
// <h4>\
// Alert!\
// </h4> <strong>Warning!</strong> Best check yo self. <a href='#' class='alert-link'>alert link</a>";
// }
// 
// /**
 // * Goes in Localstorage and returns the two teams in the form of {home:<value> , away:<value>}
 // * @param {Object} i_match_id
 // */